package com.dbh.alg.datastructure;


/**
 * 链表结构
 * @author 董帮辉
 * @date 2025/4/28
 **/
public class ListNode {
    /**
     * 值
     */
    int val;

    /**
     * 下一节点
     */
    ListNode next;
    ListNode() {

    }

    public ListNode(int val) {
        this.val = val;
    }

    public ListNode(int val, ListNode next) {
        this.val = val; this.next = next;
    }

    public static ListNode of(int... vals) {
        if (vals.length == 0) {
            return null;
        }
        // 创建头节点
        ListNode head = new ListNode(vals[0]);
        // 用于遍历的指针
        ListNode p = head;
        // 从第二个元素开始依次添加到链表末尾
        for (int i = 1; i < vals.length; i++) {
            p.next = new ListNode(vals[i]);
            p = p.next;
        }
        return head;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder(64);
        sb.append("[");
        ListNode p = this;
        while (p != null) {
            sb.append(p.val);
            if (p.next != null) {
                sb.append(",");
            }
            p = p.next;
        }
        sb.append("]");
        return sb.toString();
    }
}
